<template>
  <detail-form :schemas="detailFormSchemas" :data="subFormData" :span="formSpan" />
</template>
<script lang="ts">
  import { useMessage } from '/@/hooks/web/useMessage';
  import { ref, watch, defineComponent } from 'vue';
  import { BasicForm } from '/@/components/Form/index';
  import { defHttp } from '/@/utils/http/axios';
  import { getDetailFormSchemas, getRefPromise } from '../../use/useAutoForm';
  import { Loading } from '/@/components/Loading';
  import DetailForm from '../../extend/form/DetailForm.vue';

  const baseUrl = '/api-online/online/cgform/api/subform';

  export default defineComponent({
    name: 'OnlineSubFormDetail',
    components: {
      BasicForm,
      Loading,
      DetailForm,
    },
    props: {
      properties: {
        type: Object,
        required: true,
      },
      mainId: {
        type: String,
        default: '',
      },
      table: {
        type: String,
        default: '',
      },
      formTemplate: {
        type: Number,
        default: 1,
      },
    },
    emits: ['formChange'],
    setup(props) {
      const formRendered = ref(false);
      const { createMessage: $message } = useMessage();
      const tableName = ref('');
      const subFormData = ref({});
      const { detailFormSchemas, createFormSchemas, formSpan } = getDetailFormSchemas(props);
      watch(
        () => props.table,
        () => {
          tableName.value = props.table;
        },
        { immediate: true }
      );
      watch(
        () => props.properties,
        () => {
          console.log('主表properties改变', props.properties);
          formRendered.value = false;
          createFormSchemas(props.properties);
          formRendered.value = true;
        },
        { deep: true, immediate: true }
      );
      watch(
        () => props.mainId,
        () => {
          console.log('主表ID改变', props.mainId);
          setTimeout(() => {
            resetSubForm();
          }, 100);
        },
        { immediate: true }
      );
      async function resetSubForm() {
        await getRefPromise(formRendered);
        subFormData.value = {};
        const { table, mainId } = props;
        if (!table || !mainId) {
          return;
        }
        let values = (await loadData(table, mainId)) || {};
        subFormData.value = values;
      }
      function loadData(table, mainId) {
        let url = `${baseUrl}/${table}/${mainId}`;
        return new Promise((resolve, reject) => {
          defHttp.get({ url }, { isTransformResponse: false }).then((res) => {
            console.log(res);
            if (res.success) {
              resolve(res.data);
            } else {
              console.log(res.msg);
              reject();
            }
          });
        }).catch(() => {
          $message.warning('子表获取数据失败:' + table);
        });
      }
      return {
        detailFormSchemas,
        subFormData,
        formSpan,
      };
    },
  });
</script>
<style scoped></style>
